import 'package:flutter/material.dart';
import 'package:flutter/cupertino.dart';
import 'function.dart';
import 'util/event.dart';
import 'model/device_model.dart';
import 'monitor_set.dart';
import 'monitor_record.dart';
import 'recharge_page.dart';

class MonitorPage extends StatefulWidget {
  @override
  _MonitorPageState createState() => new _MonitorPageState();
}

class _MonitorPageState extends State<MonitorPage> {
  Color mainColor = Colors.deepOrange;
  String uid = "";
  String balance = "0";
  String buycount = "";
  var pushrecord = [];
  var pushdevice = [];
  List<DeviceModel> devices = [];
  _MonitorPageState() {
    eventBus.on<Event>().listen((event) async {
      switch (event.msg) {
        case "theme":
          setTheme();
          break;
        case "monitor":
          initMonitor();
          break;
      }
    });
    setTheme();
  }
  reloadMonitor() async {
    this.uid = await getStorage("uid");
    var info = await getUserInfo(this.uid);
    this.pushrecord = info['msg']['pushrecord'];
    this.pushdevice = info['msg']['pushdevice'];
    this.buycount = info['msg']['buy_count'];
    this.balance = info['msg']['balance'];
    setState(() {});

    devices.forEach((d) {
      for (var push in pushdevice) {
        if (d.account == push['phone']) {
          d.ispush = "1";
          break;
        }
      }
    });
    setState(() {});
  }

  initMonitor() async {
    devices = [];
    this.uid = await getStorage("uid");
    var info = await getUserInfo(this.uid);
    if (info == null) {
      return;
    }
    this.pushrecord = info['msg']['pushrecord'];
    this.pushdevice = info['msg']['pushdevice'];
    this.buycount = info['msg']['buy_count'];
    this.balance = info['msg']['balance'];
    setState(() {});
    var existDevices = await getDevices();

    if (existDevices != null) {
      existDevices.forEach((d) {
        DeviceModel device = new DeviceModel().fromMap(d);
        device.ispush = "0";
        for (var push in pushdevice) {
          if (device.account == push['phone']) {
            device.ispush = "1";
            break;
          }
        }
        devices.add(device);
      });
      setState(() {});
    }
  }

  save() async {
    List saveDevice = [];
    devices.forEach((device) {
      if ("1" == device.ispush) {
        saveDevice.add({"phone": device.account, "pwd": device.password});
      }
    });

    var saveRes = await saveMonitor(saveDevice, this.uid);
    if (saveRes['code'] == 1) {
      toast(saveRes['msg']);
      reloadMonitor();
    }
  }

  setTheme() {
    themeColor.then((color) {
      mainColor = color;
      setState(() {});
    });
  }

  Widget _buildDevice(DeviceModel device) {
    return new ListTile(
      title: new Text("${device.device_name}-${device.account}"),
      trailing: new CupertinoSwitch(
          value: device.ispush == "1",
          onChanged: (value) {
            device.ispush = value ? "1" : "0";
            setState(() {});
          }),
    );
  }

  @override
  Widget build(BuildContext context) {
    return new MaterialApp(
      theme: new ThemeData(
        accentColor: mainColor,
        primaryColor: mainColor,
      ),
      home: new Scaffold(
        appBar: new CupertinoNavigationBar(
          actionsForegroundColor: Colors.white,
          backgroundColor: mainColor,
          leading: new CupertinoButton(
            child: new Text(
              "设置",
              style: new TextStyle(fontSize: 16.0, color: Colors.white),
            ),
            onPressed: () {
              Navigator.of(context).push(
                new CupertinoPageRoute(
                  builder: (content) {
                    return new MonitorSetPage(mainColor);
                  },
                ),
              );
            },
            padding: EdgeInsets.zero,
          ),
          middle: new Text(
            "实时监控",
            style: new TextStyle(
              color: Colors.white,
              fontWeight: FontWeight.normal,
            ),
          ),
          trailing: new CupertinoButton(
            padding: EdgeInsets.zero,
            child: new Text(
              "保存",
              style: new TextStyle(fontSize: 16.0, color: Colors.white),
            ),
            pressedOpacity: 0.8,
            onPressed: save,
            minSize: 24.0,
          ),
        ),
        body: new Scrollbar(
          child: new ListView(
            children: <Widget>[
              new Row(
                children: <Widget>[
                  new Expanded(
                    child: new FlatButton(
                      padding: EdgeInsets.only(top: 10.0, bottom: 10.0),
                      onPressed: () {},
                      child: new Column(
                        children: <Widget>[
                          new ImageIcon(
                            AssetImage("images/wky.png"),
                            color: Colors.grey,
                            size: 32.0,
                          ),
                          new SizedBox(
                            height: 5.0,
                          ),
                          new Text("开通设备"),
                          new Text("${pushdevice.length}/$buycount"),
                        ],
                      ),
                    ),
                  ),
//                  new Expanded(
//                    child: new FlatButton(
//                      padding: EdgeInsets.only(top: 10.0, bottom: 10.0),
//                      onPressed: () {
//                        toast("暂不支持充值");
////                        Navigator.of(context).push(
////                          new CupertinoPageRoute(
////                            builder: (content) {
////                              return new RechargePage(mainColor);
////                            },
////                          ),
////                        );
//                      },
//                      child: new Column(
//                        children: <Widget>[
//                          new ImageIcon(
//                            AssetImage("images/balance.png"),
//                            color: Colors.red,
//                            size: 32.0,
//                          ),
//                          new SizedBox(
//                            height: 5.0,
//                          ),
//                          new Text("点数余额"),
//                          new Text("$balance"),
//                        ],
//                      ),
//                    ),
//                  ),
                  new Expanded(
                    child: new FlatButton(
                      padding: EdgeInsets.only(top: 10.0, bottom: 10.0),
                      onPressed: () {
                        Navigator.of(context).push(
                          new CupertinoPageRoute(
                            builder: (content) {
                              return new MonitorRecord(pushrecord, mainColor);
                            },
                          ),
                        );
                      },
                      child: new Column(
                        children: <Widget>[
                          new ImageIcon(
                            AssetImage("images/pushrecord.png"),
                            color: Colors.orangeAccent,
                            size: 32.0,
                          ),
                          new SizedBox(
                            height: 5.0,
                          ),
                          new Text("异常记录"),
                          new Text("${pushrecord.length}条"),
                        ],
                      ),
                    ),
                  ),
                ],
              ),
              new Column(
                children: devices.map(_buildDevice).toList(),
              ),
            ],
          ),
        ),
      ),
    );
  }
}
